package com.feeyo.groundservice.zxing.activity

import com.feeyo.groundservice.base_util.post
import com.feeyo.groundservice.base_util.toastCenter
import com.feeyo.groundservice.zxing.BaseZxingActivity
import com.feeyo.groundservice.zxing.constant.ZxingConstant
import com.feeyo.groundservice.zxing.event.ScanCodeResultEvent
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeResult
import com.journeyapps.barcodescanner.DefaultDecoderFactory
import com.therouter.router.Route

/**
 * This sample performs continuous scanning, displaying the barcode and source image whenever
 * a barcode is scanned.
 */
@Route(path = ZxingConstant.OnlyBarCodeCaptureActivity)
internal class OnlyBarCodeCaptureActivity : BaseZxingActivity() {

    private val formats =
        listOf(
            BarcodeFormat.UPC_A,
            BarcodeFormat.UPC_E,
            BarcodeFormat.EAN_13,
            BarcodeFormat.EAN_8,
            BarcodeFormat.RSS_14,
            BarcodeFormat.CODE_39,
            BarcodeFormat.CODE_93,
            BarcodeFormat.CODE_128,
            BarcodeFormat.ITF,
            BarcodeFormat.PDF_417,
            BarcodeFormat.RSS_EXPANDED
        )

    init {
        prompt = "请将条形码置于框内，即可自动扫描"
    }

    override fun differentSettings() {

        binding.barcodeScanner.apply {
            barcodeView.decoderFactory = DefaultDecoderFactory(formats)
            decodeContinuous(callback)
        }
    }

    override fun validateCodeFormat(result: BarcodeResult): Boolean {
        if (result.barcodeFormat !in formats) {
            toastCenter("请扫描条形码")
            return false
        }
        return true
    }

    override fun dataCallback(format: String) {
        scanCallback?.onScanCodeSuccess(lastText,format) ?: ScanCodeResultEvent(lastText,format).post()
        finish()
    }
}
